(async function () {
    // 验证是否登录
    const resp = await API.profile();
    const data = resp.data;
    if (!data) {
        alert("未登录或登录已过期，请重新登录");
        location.href = './login.html';
        return;
    }

    // 登陆状态下运行以下代码
    const doms = {
        aside: {
            nickname: document.querySelector('#nickname'),
            loginId: document.querySelector('#loginId'),
        },
        close: document.querySelector('.close'),
        chatContainer: document.querySelector('.chat-container'),
        txtMsg: document.querySelector('#txtMsg'),
        messageContainer: document.querySelector('.msg-container'),
    }
    function setUserInfo() {
        doms.aside.nickname.innerText = data.nickname;
        doms.aside.loginId.innerText = data.loginId;
    }
    setUserInfo();

    // 注销
    doms.close.addEventListener('click', () => {
        API.loginOut();
        location.href = './login.html';
    });

    // 添加聊天记录
    function addChat(chatInfo) {

        const div = document.createElement('div');
        div.classList.add('chat-item');

        if (chatInfo.from) {
            div.classList.add('me');
        }

        const img = document.createElement('img');
        img.className = 'chat-avatar';
        img.src = chatInfo.from ? "./asset/avatar.png" : "./asset/robot-avatar.jpg";

        const content = document.createElement('div');
        content.className = 'chat-content';
        content.innerText = chatInfo.content;

        const date = document.createElement('div');
        date.className = 'chat-date';
        data.innerText = formatDate(chatInfo.createdAt);

        div.appendChild(img);
        div.appendChild(content);
        div.appendChild(date);

        doms.chatContainer.appendChild(div);
    }

    // 格式化时间戳
    function formatDate(time) {
        const date = new Date(time);
        const year = date.getFullYear();
        const month = (date.getMonth + 1).toString().padStart(2, '0');
        const day = date.getDate().toString().padStart(2, '0');
        const hour = date.getHours().toString().padStart(2, '0');
        const minute = date.getMinutes.toString().padStart(2, '0');
        const second = date.getSeconds.toString().padStart(2, '0');

        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    }

    // 加载历史记录
    async function loadHistory() {
        const resp = await API.getHistory();
        for (const item of resp.data) {
            addChat(item);
        }
        scrollBottom();
    }
    loadHistory();

    // 滚动条拉到底部
    function scrollBottom() {
        doms.chatContainer.scrollTop = doms.chatContainer.scrollHeight;
    }

    async function sendChat() {
        const content = doms.txtMsg.value.trim();// 去掉首尾空格
        if (!content) {
            return;
        }
        addChat({
            from: data.id,
            to: null,
            createdAt: Date.now(),
            content,
        });
        doms.txtMsg.value = '';
        scrollBottom();
        const resp = await API.sendChat(content);
        addChat({
            from: null,
            to: data.loginId,
            ...resp.data,
        });
        scrollBottom();
    }

    doms.messageContainer.addEventListener('submit', (e) => {
        e.preventDefault();
        sendChat();
    })
})();
